package com.guicent.geekai.controller;

import com.guicent.geekai.entity.ChatMessage;
import com.guicent.geekai.entity.ChatSession;
import com.guicent.geekai.entity.dto.ChatRequestDTO;
import com.guicent.geekai.service.ChatService;
import com.guicent.geekai.util.R;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 聊天控制器
 *
 * @author xiaojiang
 * @date 2025/03/17
 */
@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Autowired
    private ChatService chatService;

    @PostMapping("/message")
    public R sendMessage(@RequestBody ChatRequestDTO chatRequestDTO) {

        Long userId = chatRequestDTO.getUserId();
        Long sessionId = chatRequestDTO.getSessionId();
        String content = chatRequestDTO.getContent();

        if (sessionId == null){
            ChatSession sessionSave = chatService.createSession(userId, content);
            Long sessionSaveId = sessionSave.getSessionId();
            return chatService.sendMessage(sessionSaveId, content);
        }

        return chatService.sendMessage(chatRequestDTO.getSessionId(), content);
    }

    /**
     * 获取会话
     *
     * @param userId 用户id
     * @return {@link ResponseEntity }<{@link List }<{@link ChatSession }>>
     */// 查询指定用户的所有会话
    @GetMapping("/sessions")
    public ResponseEntity<List<ChatSession>> getSessions(@RequestParam Long userId) {
        List<ChatSession> sessions = chatService.getSessionsByUserId(userId);
        return ResponseEntity.ok(sessions);
    }

    /**
     * 获取消息
     *
     * @param sessionId 会话id
     * @return {@link ResponseEntity }<{@link List }<{@link ChatMessage }>>
     */// 查询指定会话中的所有消息
    @GetMapping("/session/{sessionId}/messages")
    public ResponseEntity<List<ChatMessage>> getMessages(@PathVariable Long sessionId) {
        List<ChatMessage> messages = chatService.getMessagesBySessionId(sessionId);
        return ResponseEntity.ok(messages);
    }
}